package com.jlnk.stockdemo.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jlnk.stockdemo.R;

import com.jlnk.stockdemo.adapter.BondsAdapter;
import com.jlnk.stockdemo.bean.BondsListResponse;
import com.jlnk.stockdemo.viewmodel.BondsViewModel;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class BondsFragment extends Fragment {
    private static final String TAG = "BondsFragment";
    private BondsViewModel bondsViewModel;
    private RecyclerView recyclerview_bonds;
    private BondsAdapter bondsAdapter;
    private List<BondsListResponse.Data.Bonds> bondsList = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_bonds, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        bondsAdapter = new BondsAdapter(bondsList);
        recyclerview_bonds = view.findViewById(R.id.recyclerview_bonds);
        recyclerview_bonds.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerview_bonds.setAdapter(bondsAdapter);

        bondsViewModel = new ViewModelProvider(this).get(BondsViewModel.class);
        bondsViewModel.getBondsListLiveData().observe(getViewLifecycleOwner(), bonds -> {
            this.bondsList.clear();
            this.bondsList.addAll(bonds);
            bondsAdapter.notifyDataSetChanged();
        });
        bondsViewModel.fetchBondsList();
    }
}
